<template>
    <!-- 第一阶段：输入账号 -->
    <el-form v-if="step === 1" :model="form" ref="formRef" label-width="200px" class="centered-form">
        <!-- 账号输入框 -->
        <el-form-item label="账号" prop="username">
            <el-input v-model="form.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="loginType">
            <el-radio-group v-model="form.loginType">
                <el-radio :value="1">老师</el-radio>
                <el-radio :value="2">学生</el-radio>
                <el-radio :value="3">家长</el-radio>
            </el-radio-group>
        </el-form-item>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">{{ buttonText }}</el-button>
            <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
    </el-form>

    <!-- 第二阶段：输入密保问题 -->
    <el-form v-if="step === 2" :model="form" ref="formRef2" label-width="200px" :rules="securityQuestionRules"
        class="centered-form">
        <!-- 动态展示密保问题 -->
        <el-form-item v-for="(question, index) in securityQuestions" :key="index" :label="question.questionName"
            :prop="'securityAnswer' + index">
            <el-input v-model="form['securityAnswer' + index]" placeholder="请输入答案"></el-input>
        </el-form-item>

        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button v-if="repeatPwd" type="primary" @click="resetPassword">下一步</el-button>
        </div>
    </el-form>
    <!-- 第三阶段：修改密码 -->
    <el-form v-if="step === 3" :model="form" ref="formRef3" :rules="passwordRules" label-width="100px"
        class="centered-form custom-form">
        <!-- 新密码输入框 -->
        <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="form.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
        </el-form-item>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="submitPasswordChange">提交修改</el-button>
        </div>
    </el-form>
</template>
<script setup>
import {
    ref,
    reactive
} from 'vue';
import {
    ElMessage
} from 'element-plus';
import apis from '@/api/index.js';
import router from '@/router';
const _api = apis()
const formRef = ref(null); // 用于第一阶段的表单
const formRef2 = ref(null); // 用于第二阶段的表单
const formRef3 = ref(null); // 用于第三阶段的表单
const step = ref(1); // 控制当前步骤：1 表示输入账号，2 表示输入密保问题，3表示修改密码
const form = reactive({
    username: '', // 用户输入的账号
    securityAnswer: '', // 用户输入的密保答案
    loginType: 1,
    confirmPassword: '', // 用户输入的确认密码
    newPassword: '', // 用户输入的新密码
});
//按钮名称
const buttonText = ref("取消")
//重置密码
const repeatPwd = ref(true)
//问题列表
const securityQuestions = ref([])
// 关闭对话框
const closeDialog = () => {
    router.push('/Login')
    // step.value = 1; // 恢复到第一个步骤
};
// 下一步操作：验证账号
const nextStep = () => {
    const username = form.username;
    if (!username) {
        ElMessage.error('账户名不能为空');
        return;  // 直接返回，阻止后续逻辑执行
    }
    // 表单验证
    formRef.value.validate((valid) => {
        if (valid) {
            //请求数据
            let url = _jwHtml + '/userSecurityRecordsInfo/listByPage'
            _api.hDoPost(url, '', form, (res) => {
                if (res.code == 0) {
                    securityQuestions.value = res.data;
                    step.value = 2; // 如果账号验证通过，进入密保问题阶段
                    // 动态生成验证规则
                    securityQuestions.value.forEach((question, index) => {
                        // 为每个问题生成对应的验证规则
                        securityQuestionRules[`securityAnswer${index}`] = [
                            { required: true, message: `请输入${question.questionName}`, trigger: 'blur' },
                        ];
                        // 同时更新表单的值
                        form[`securityAnswer${index}`] = '';
                    });
                    if (res.data.length == 0) {
                        repeatPwd.value = false;
                        ElMessage.error("当前用户没有设置密保问题，请联系管理员处理");
                    }
                }
                else {
                    ElMessage.error(res.msg);
                }
            })
        }
    });
};
//密码验证规则
const passwordRules = {
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入新密码'));
                } else {
                    // 判断密码中包含哪些类型的字符
                    const hasUpperCase = /[A-Z]/.test(value);  // 大写字母
                    const hasLowerCase = /[a-z]/.test(value);  // 小写字母
                    const hasNumber = /\d/.test(value);        // 数字
                    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(value);  // 特殊字符
                    const types = [hasUpperCase, hasLowerCase, hasNumber, hasSpecialChar];
                    const typeCount = types.filter(Boolean).length; // 计算满足条件的类型数
                    if (typeCount < 3) {
                        callback(new Error('密码需包含三种以上（大写字母、小写字母、数字、特殊字符）'));
                    } else {
                        callback();  // 验证通过
                    }
                }
            },
            trigger: 'blur'
        }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== form.newPassword) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
};
// 验证规则
const securityQuestionRules = reactive({});
// 重置密码操作：验证密保答案
const resetPassword = () => {
    // 表单验证
    formRef2.value.validate((valid) => {
        if (valid) {
            // 准备要提交的数据
            const dataToSubmit = {
                username: form.username,
                loginType: form.loginType,
                securityQuestions: securityQuestions.value.map((question, index) => ({
                    questionId: question.questionId,
                    answer: form['securityAnswer' + index]
                }))
            }
            //请求数据
            let url = _jwHtml + '/userSecurityRecordsVerify/listByPage'
            _api.hDoPost(url, '', dataToSubmit, (res) => {
                if (res.code == 0) {
                    ElMessage({
                        message: "密保验证通过",
                        type: 'success'
                    })
                    step.value = 3; // 如果密保验证通过，进入修改密码阶段
                }
                else {
                    ElMessage.error(res.msg);
                }
            })
        }
    });
};
//加密密码传输
function b64EncodeUnicode(str) {
    return btoa(unescape(encodeURIComponent(str)))
};
//重置密码操作
const submitPasswordChange = () => {
    // 表单验证
    formRef3.value.validate((valid) => {
        if (valid) {
            // 密码修改提交
            if (form.newPassword === form.confirmPassword) {
                console.log(form)
                let params = {
                    username: form.username,
                    type: form.loginType,
                    newPwd: b64EncodeUnicode(form.confirmPassword)
                }
                //请求数据
                let url = _jwHtml + '/sys/userPwdInfo'
                _api.hDoPost(url, '', params, (res) => {
                    if (res.code == 0) {
                        // 执行密码修改逻辑
                        ElMessage({
                            message: "密码已成功修改",
                            type: 'success'
                        })
                    }
                    else {
                        ElMessage.error(res.msg);
                    }
                })
                // router.push('/Login')
            } else {
                ElMessage.error("密码和确认密码不匹配");
            }
        }
    });

}
</script>
<style>
/* 表单容器居中样式 */
.centered-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
}

/* 防止表单项间距过大 */
.centered-form .el-form-item {
    margin-bottom: 20px;
}
</style>